<?php

namespace App\Formats;

use App\Common\Libs\ArrayHelper;
use App\Consts\GlobalConst;
use App\Models\IndexDynamic;
use App\Models\UserMessageLikeSend;

class LikeFormat extends BaseFormat
{
    public const USER_LIKE_LIST = 'userLikeList';

    public function formatLikeList($likes, $currentUserId, $formatScene)
    {
        switch ($formatScene) {
            case self::SELF_LIST:
            case self::USER_LIKE_LIST:
                return self::formatBySelfList($likes, $currentUserId);
        }

        return [];
    }

    public static function formatBySelfList($likes, $currentUserId)
    {
        $targetIdArr = ArrayHelper::getColumn($likes, 'target_id');

        $dynamics = IndexDynamic::getInstance()
            ->select(['target_id'])
            ->whereIn('dynamic_id', (array)$targetIdArr)
            ->get();
        $articleArr = formats()->ArticleFormat->formatArticleList(ArrayHelper::getColumn($dynamics, 'target_id'), $currentUserId, ArticleFormat::HOME_COLLECT_LIST);
        $articleArr = ArrayHelper::index($articleArr, 'id');

        $noteArr = formats()->NoteFormat->formatNoteList($targetIdArr, $currentUserId, NoteFormat::HOME_COLLECT_LIST);
        $noteArr = ArrayHelper::index($noteArr, 'id');

        $likeArr = self::getLikeArrByTargetIds($currentUserId, $targetIdArr);

        $list = [];
        /**
         * @var UserMessageLikeSend $like
         */
        foreach ($likes as $like) {
            if ($like->target_type == GlobalConst::TARGET_TYPE_DYNAMIC && isset($articleArr[$like->target_id])) {
                $list[] = ArrayHelper::merge($articleArr[$like->target_id], [
                    'like_id' => $like->message_id,
                    'created_at' => $like->updated_at,
                    'target_type' => GlobalConst::TARGET_TYPE_ARTICLE,
                ]);
            }
            if ($like->target_type == GlobalConst::TARGET_TYPE_NOTE && isset($noteArr[$like->target_id])) {
                $list[] = ArrayHelper::merge($noteArr[$like->target_id], [
                    'like_id' => $like->message_id,
                    'created_at' => $like->updated_at,
                    'is_like' => isset($likeArr[$like->target_id]) && $likeArr[$like->target_id]->is_deleted == GlobalConst::IS_NOT_DELETE,
                    'target_type' => GlobalConst::TARGET_TYPE_NOTE,
                ]);
            }
        }

        return $list;
    }

    public static function getLikeArrByTargetIds($userId, $targetIds, $select = ['target_id', 'is_deleted'])
    {
        $result = UserMessageLikeSend::getModel($userId)
            ->select($select)
            ->where('sender_id', $userId)
            ->whereIn('target_id', (array)$targetIds)
            ->get();

        return ArrayHelper::index($result, 'target_id');
    }
}
